<?php
/**
 *
 */
Class SessionRedis{

    //REDIS连接对象
    private $redis;

    //SESSION有效时间
    private $expire;

    public function execute(){
        session_set_save_handler(
            array(&$this,'open'),
            array(&$this,'close'),
            array(&$this,'read'),
            array(&$this,'write'),
            array(&$this,'destroy'),
            array(&$this,'gc')
        );
    }

    /**
     * 打开SESSION
     * @param $path
     * @param $name
     * @return mixed
     */
    public function open($path,$name){
        $this->expire = C('SESSION_EXPIRE') ? C('SESSION_EXPIRE') : ini_get('session.gc_maslifetime');
        $this->redis = new Redis();
        return $this->redis->connect(C('REDIS_HOST'),C('REDIS_PORT'));
    }

    /**
     * 关闭SESSION
     * @return mixed
     */
    public function close(){
        return $this->redis->close();
    }

    /**
     * 读取SESSION
     * @param $id
     * @return string
     */
    public function read($id){
        $id = C('SESSION_PREFIX') . $id;
        $data = $this->redis->get($id);
        return $data ? $data : '什么都没有';
    }

    /**
     * 写入SESSION
     * @param $id
     * @param $data
     */
    public function write($id,$data){
        $id = C('SESSION_PREFIX') . $id;
        return $this->redis->set($id,$data,$this->expire);
    }

    /**
     * 销毁SESSION
     * @param $id
     * @return mixed
     */
    public function destroy($id){
        $id = C('SESSION_PREFIX') . $id;
        return $this->redis->delete($id);
    }

    /**
     * 垃圾处理
     * @param $maxLifeTime
     * @return bool
     */
    public function gc($maxLifeTime){
        return true;
    }
}

?>